import axios from 'axios'
import router from './router'
import Vue from 'vue'
import ElementUI from 'element-ui'
import { Loading } from 'element-ui';

var root = process.env.VUE_APP_BASE_API

let loading;
 
const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  });
};

 
const endLoading = () => {
  loading.close();
};

axios.interceptors.request.use(config => {
  // --请求之前重新拼装url--
  config.nol = config.nol == undefined ? true : false
  if(config.nol){
    startLoading();
  }

  config.url = root + config.url
  if (
    config.url === '/url/v1/login/reg' ||
    config.url === '/url/v1/login/login'
  ) {
    // 如果是登录和注册操作，则不需要携带header里面的token
  } else {
    if (sessionStorage.id) {
      config.headers = {
        Authorization: sessionStorage.id
      }
    }
  }
  return config
})

axios.interceptors.response.use(
  response => {
    if (response.data.errno === 999) {
      router.replace('/')
      // console.log('token过期')
    }
    if (response.data.code  ===200) {
      endLoading();
    }
    if (response.data.code  ===500) {
      // this.$message({
      //   type: "info",
      //   message: response.data.message
      // });
      endLoading();
    }
    return response
  },
  error => {
    return error
  }
)

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (sessionStorage.id) {
      // 获取当前的token是否存在
      // console.log('token存在')
      next()

      // if (to.name !== 'application') {
      //   next()
      // } else {
      //   if (
      //     sessionStorage.party_id !== 'null') {
      //     next()
      //   } else {
      //     alert('请先成为党组织！')
      //     next({
      //       path: '/', // 将跳转的路由path作为参数，登录成功后跳转到该路由
      //       query: { redirect: to.fullPath }
      //     })
      //   }
      // }
    } else {
      alert('请先登录！')
      next({
        path: '/login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 如果不需要权限校验，直接进入路由界面
    next()
  }
})

export default axios
